﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MoetutuServer.Helper
{
    class ImageHelper
    {       /// <summary>
            /// 无损压缩图片
            /// </summary>
            /// <param name="sFile">原图片地址</param>
            /// <param name="dFile">压缩后保存图片地址</param>
            /// <param name="flag">压缩质量（数字越小压缩率越高）1-100</param>
            /// <param name="size">压缩后图片的最大大小</param>
            /// <param name="sfsc">是否是第一次调用</param>
            /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 2500, bool sfsc = true)
        {
            //如果是第一次调用，原始图像的大小小于要压缩的大小，则直接复制文件，并且返回true


            if (FileHelper.JudgementOfSize(sFile, size))
            {
                Console.WriteLine("无需压缩");
           
                if (sFile != dFile)
                {
                    
                    File.Copy(sFile, dFile, true);
                }
                return true;

            }

            Image iSource;
            ImageFormat tFormat;
            int dHeight, dWidth, sW, sH;
            Resiz(sFile, out iSource, out tFormat, out dHeight, out dWidth, out sW, out sH);

            using (Bitmap ob = new Bitmap(dWidth, dHeight))
            {
                using (Graphics GraphicsPint = Graphics.FromImage(ob))
                {

                    GraphicsPint.Clear(Color.White);
                    GraphicsPint.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    GraphicsPint.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    GraphicsPint.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                    GraphicsPint.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

                }


                iSource.Dispose();
                ImgSave(sFile, dFile, flag, size, tFormat, ob);

            }
            return true;

        }
        /// <summary>
        /// 重新调整大小 
        /// </summary>
        /// <param name="sFile"></param>
        /// <param name="iSource"></param>
        /// <param name="tFormat"></param>
        /// <param name="dHeight"></param>
        /// <param name="dWidth"></param>
        /// <param name="sW"></param>
        /// <param name="sH"></param>
        private static void Resiz(string sFile, out Image iSource, out ImageFormat tFormat, out int dHeight, out int dWidth, out int sW, out int sH)
        {
            iSource = Image.FromFile(sFile);
            tFormat = iSource.RawFormat;
            dHeight = iSource.Height / 2;
            dWidth = iSource.Width / 2;
            sW = 0;
            sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }
        }
        /// <summary>
        /// 检测图片是否能正常打开 用save事件触发崩溃，如果崩溃则代表图片不正常
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static bool ImgExistence(string FileName) {
            string TempPath = StaticValue.TempPath + DateTime.Now.ToFileTime() + ".jpg";
            try
            {
                using (Image LoadImage = Image.FromFile(FileName)) {
                LoadImage.Save(TempPath);
                }

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("文件打开错误"+FileName);
                Console.WriteLine(ex.Message);
                return false;
            }
            finally {
                FileHelper.FileDelete(TempPath);
            }
       

        }
        private static void ImgSave(string sFile, string dFile, int flag, int size, ImageFormat tFormat, Bitmap ob)
        {
            using (ob)
            {
                //以下代码为保存图片时，设置压缩质量
                EncoderParameters ep = new EncoderParameters();

                long[] qy = new long[1];
                qy[0] = flag;//设置压缩的比例1-100
                EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
                ep.Param[0] = eParam;
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();

                ImageCodecInfo jpegICIinfo = null;

                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                    flag = flag - 10;

                    if (!FileHelper.JudgementOfSize(dFile, size)) 
                     CompressImage(sFile, dFile, flag, size, false);
                }
                else
                {
                    ob.Save(dFile, tFormat);
                    ob.Dispose();

                }

            }

        }
    }
}
